import re
from typing import Optional, TypeVar

VAR_PATTERN = re.compile(r"\$\{(\w+)\}")

T = TypeVar('T', str, list, dict)

# 通过正则表达式'${my_var}'递归替换字符串中变量对应的值
def handle(
        data: T,
        var: Optional[dict] = None,
        global_var: Optional[dict] = None
) -> T:
    final_var = {**(global_var or {}), **(var or {})}

    def replace_var(key: str) -> str:
        return str(final_var.get(key, f"${{{key}}}"))

    if isinstance(data, str):
        return VAR_PATTERN.sub(lambda m: replace_var(m.group(1)), data)
    elif isinstance(data, list):
        return [handle(item, var, global_var) for item in data]
    elif isinstance(data, dict):
        return {k: handle(v, var, global_var) for k, v in data.items()}
    else:
        return data
